package org.yi.web.category.entity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.yi.core.annotation.TableBind;
import org.yi.core.common.Constants;

import com.jfinal.plugin.activerecord.Model;

@TableBind(name="f_category")
public class CategoryEntity extends Model<CategoryEntity>{

	private static final long serialVersionUID = 1L;

	public static CategoryEntity dao = new CategoryEntity();

	public Map<String,Object> toMap() {
		return super.getAttrs();
	}
	
	public CategoryEntity getByTitle(String title) {
		String sql = "select * from f_category where title = ?";
		return dao.findFirst(sql, title);
	}
	
	public CategoryEntity getByAlias(String c) {
		String sql = "select * from f_category where alias = ?";
		return dao.findFirst(sql, c);
	}
	
	public CategoryEntity getById(String id) {
		String sql = "select * from f_category where id = ?";
		return dao.findFirst(sql, id);
	}
	
	public List<CategoryEntity> getAllBySeq() {
		return CategoryEntity.dao.find("select * from f_category order by seq asc, id desc");
	}
	
	public List<Map<String, Object>> getAll() {
		List<CategoryEntity> list = CategoryEntity.dao.getAllBySeq();
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		for(CategoryEntity c1 : list) {
			Object pid = c1.get("pid");
			if(pid == null || String.valueOf(pid).length() == 0 ) {
				List<Map<String, Object>> subCategories = getSubCategories(list, c1, 1);
				c1.toMap().put("sub", subCategories);
				resultList.add(c1.toMap());
			}
		}
		return resultList;
	}
	
	private List<Map<String, Object>> getSubCategories(List<CategoryEntity> list, CategoryEntity parent, Integer level) {
		List<Map<String, Object>> subList = new ArrayList<Map<String, Object>>();
		for(CategoryEntity c : list) {
			Long cpid = c.getLong("pid");
			if(cpid == parent.getLong("id") && level < Constants.MAX_CATEGORY_GRADE) {
				List<Map<String, Object>> subCategories = getSubCategories(list, c, level + 1);
				c.toMap().put("sub", subCategories);
				subList.add(c.toMap());
			}
		}
		return subList;
	}

	public List<CategoryEntity> getSubList(String id) {
		String sql = "select * from f_category where pid = ?";
		return dao.find(sql, id);
	}
	
	public Map<String, String> getIdTitleMap(){
		Map<String, String> map = new HashMap<String, String>();
		String sql = "select * from f_category";
		List<CategoryEntity> list = dao.find(sql);
		for(CategoryEntity c: list) {
			map.put("c"+c.getLong("id"), c.getStr("title"));
		}
		return map;
	}

	public List<CategoryEntity> getAllSub() {
		String sql = "select * from f_category where pid > 0";
		return dao.find(sql);
	}

	public Object getIdAliasMap() {
		Map<String, String> map = new HashMap<String, String>();
		String sql = "select * from f_category";
		List<CategoryEntity> list = dao.find(sql);
		for(CategoryEntity c: list) {
			map.put("c"+c.getLong("id"), c.getStr("alias"));
		}
		return map;
	}

}
